//
//  ChooseFileViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "ChooseFileViewController.h"
#import "ChooseFileTableViewCell.h"
#import "ImportAudioViewController.h"
#import "AVPlayerManager.h"
#import "FileManager.h"
#import "RecordEditViewController.h"
#import "LocalRecordModel.h"

@interface ChooseFileViewController ()<AVPlayerDelegate, UIScrollViewDelegate, UIDocumentInteractionControllerDelegate> {
    NSArray             *contentArr;
    NSArray             *resultArr;
    LocalRecordModel    *playModel;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (nonatomic, strong) UIDocumentInteractionController *documentInteraction;

@end

@implementation ChooseFileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtn];

    if (self.type == 3) {
        self.title = @"导出";
    } else {
        self.title = @"选择音频";
        [((UIButton *)[self addRigthBtn:@"导入"]) addTarget:self action:@selector(importAudioPress) forControlEvents:UIControlEventTouchUpInside];
    }
        
    [self initView];
    [self reloadView];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
    [self reloadView];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;
}

- (void)dealloc {
    for (LocalRecordModel *model in contentArr) {
        model.isSelected = NO;
    }
    self.sureBtn.enabled = NO;
}

- (IBAction)surePress {
    NSMutableArray *mutArr = [NSMutableArray array];
    for (LocalRecordModel *model in contentArr) {
        if (model.isSelected) {
            [mutArr addObject:model];
        }
    }
    if (self.type == 2) {
        if (self.ChooseFileHandle) {
            self.ChooseFileHandle(mutArr);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        RecordEditViewController *viewCon = [[RecordEditViewController alloc] initWithNibName:@"RecordEditViewController" bundle:nil];
        viewCon.contentArr = mutArr;
        [self.navigationController pushViewController:viewCon animated:YES];
    }
}

- (void)trackPlayDidEnd {
    playModel.isPlaying = NO;
    NSIndexPath *loadIndexPath = [NSIndexPath indexPathForRow:[contentArr indexOfObject:playModel] inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:loadIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)reloadView {
    NSMutableArray *dataMutArr = [NSMutableArray array];
    for (LocalRecordModel *model in [UserManger currentLoggedInUser].files) {
        [dataMutArr addObject:[model copy]];
    }
    contentArr = dataMutArr;
    resultArr = contentArr;
    [self.tableView reloadData];
    [self reloadChooseButton];
}

- (void)reloadChooseButton {
    BOOL hasChoose = NO;
    for (LocalRecordModel *model in contentArr) {
        if (model.isSelected) {
            hasChoose = YES;
            break;
        }
    }
    self.sureBtn.enabled = hasChoose;
}

- (void)importAudioPress {
    ImportAudioViewController *viewCon = [[ImportAudioViewController alloc] initWithNibName:@"ImportAudioViewController" bundle:nil];
    viewCon.type = 1;
    viewCon.ReloadHandle = ^{
        [self reloadView];
    };
    CustomNavigationCoutroller *navCon = [[CustomNavigationCoutroller alloc] init];
    navCon.viewControllers = @[viewCon];
    navCon.modalPresentationStyle = UIModalPresentationFullScreen;
    [[UIViewControllerCJHelper findCurrentShowingViewController].navigationController presentViewController:navCon animated:YES completion:nil];
}

#pragma mark - UITableView datasource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return resultArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ChooseFileCell";
    ChooseFileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ChooseFileTableViewCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.ClickHandle = ^(LocalRecordModel * _Nonnull model) {
        if (self->playModel != model) {
            if (self->playModel) {
                self->playModel.isPlaying = NO;
                NSIndexPath *loadIndexPath = [NSIndexPath indexPathForRow:[self->resultArr indexOfObject:self->playModel] inSection:0];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:loadIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            }
            self->playModel = model;
            [[AVPlayerManager manager] setAVPlayerURL:[NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:model.fileName]]];
        }
    };
    cell.model = [resultArr objectAtIndex:indexPath.row];
    if (self.type == 3 || self.type == 4) {
        [cell hiddenChooseIcon];
    } 
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    if (self.type == 3) {
        LocalRecordModel *model = [resultArr objectAtIndex:indexPath.row];;
        self.documentInteraction.URL = [NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:model.fileName]];
        BOOL canOpen = [self.documentInteraction presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
        if (!canOpen) {
            [self showHUDAlert:@"无法打开该文件"];
        }
    } else if (self.type == 4) {
        if (self.ChooseFileHandle) {
            self.ChooseFileHandle([NSArray arrayWithObject:[self->resultArr objectAtIndex:indexPath.row]]);
        }
    } else {
        LocalRecordModel *model = [resultArr objectAtIndex:indexPath.row];;
        model.isSelected = !model.isSelected;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        [self reloadChooseButton];
    }
}


- (void)initView {
    if (self.type == 3 || self.type == 4) {
        [self.tableView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight))];
        self.bottomView.hidden = YES;
        self.tableView.contentInset = UIEdgeInsetsMake(10, 0, IS_iPhoneX_Bottom, 0);
    } else {
        [self.tableView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + IS_iPhoneX_Bottom + 64))];
        [self.bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - 64, SCREEN_WIDTH_DEVICE, IS_iPhoneX_Bottom + 64)];
        self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    }
    [self.sureBtn setBackgroundImage:getColorToImage(ThemeColor) forState:UIControlStateNormal];
    [self.sureBtn setBackgroundImage:getColorToImage(TextGrayColor) forState:UIControlStateDisabled];

}

#pragma mark - UIDocumentInteractionControllerDelegate
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
    return self.view.frame;
}

#pragma mark - Lazy
- (UIDocumentInteractionController *)documentInteraction{
    if (!_documentInteraction) {
        _documentInteraction = [[UIDocumentInteractionController alloc] init];
        _documentInteraction.delegate = self;
    }
    return _documentInteraction;
}
@end
